<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改患者')" />
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-patient-edit" th:object="${tPatient}">
        <input name="id" th:field="*{id}" type="hidden">

        <!-- 患者基本信息 -->
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">患者姓名：</label>
                <div class="col-sm-8">
                    <input name="name" th:field="*{name}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">身份证号：</label>
                <div class="col-sm-8">
                    <input name="idNumber" th:field="*{idNumber}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出生日期：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="birthDate" th:value="${#dates.format(tPatient.birthDate, 'yyyy-MM-dd')}" class="form-control" type="text" required>
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">年龄：</label>
                <div class="col-sm-8">
                    <input name="age" th:field="*{age}" class="form-control" type="text" required readonly>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">家庭住址：</label>
                <div class="col-sm-8">
                    <input name="address" th:field="*{address}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">紧急联系人：</label>
                <div class="col-sm-8">
                    <input name="emergencyContact" th:field="*{emergencyContact}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">紧急联系人电话：</label>
                <div class="col-sm-8">
                    <input name="emergencyContactPhone" th:field="*{emergencyContactPhone}" class="form-control" type="text" required>
                </div>
            </div>
        </div>

        <!-- 科室-病房-床位级联 -->
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">所属科室：</label>
                <div class="col-sm-8">
                    <select name="departmentId" id="departmentId" class="form-control" required>
                        <option value="">请选择科室...</option>
                        <option th:each="dept:${depts}"
                                th:value="${dept.deptId}"
                                th:text="${dept.deptName}"
                                th:selected="${dept.deptId == tPatient.departmentId}"></option>
                    </select>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">所属病房：</label>
                <div class="col-sm-8">
                    <select name="wardId" id="wardId" class="form-control" required disabled>
                        <option value="">加载中...</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">床位：</label>
                <div class="col-sm-8">
                    <select name="bedId" id="bedId" class="form-control" required disabled>
                        <option value="">加载中...</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 医护人员 -->
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">主治医生：</label>
                <div class="col-sm-8">
                    <select name="attendingDoctorId" id="attendingDoctorId" class="form-control" required>
                        <option th:each="doctor:${tDoctors}"
                                th:value="${doctor.id}"
                                th:text="${doctor.name}"
                                th:selected="${doctor.id == tPatient.attendingDoctorId}"></option>
                    </select>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">责任护士：</label>
                <div class="col-sm-8">
                    <select name="responsibleNurseId" id="responsibleNurseId" class="form-control" required>
                        <option th:each="nurse:${tNurses}"
                                th:value="${nurse.id}"
                                th:text="${nurse.name}"
                                th:selected="${nurse.id == tPatient.responsibleNurseId}"></option>
                    </select>
                </div>
            </div>
        </div>
    </form>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />

<script th:inline="javascript">
    var prefix = ctx + "system/patient";

    // 全局提交函数
    window.submitHandler = function() {
        if ($("#form-patient-edit").valid()) {
            $.operate.save(prefix + "/edit", $('#form-patient-edit').serialize());
        }
    };

    $(function() {
        // 初始化表单验证
        $("#form-patient-edit").validate({
            focusCleanup: true,
            rules: {
                wardId: {
                    required: true,
                    validWard: true
                },
                bedId: {
                    validBed: true
                }
            }
        });

        // 科室选择事件
        $('#departmentId').on('change', function() {
            const deptId = $(this).val();
            const wardSelect = $('#wardId');
            const bedSelect = $('#bedId');


            wardSelect.prop('disabled', true).empty().append('<option value="">加载中...</option>');
            bedSelect.prop('disabled', true).empty().append('<option value="">加载中...</option>');

            if (!deptId) return;

            // 加载病房
            $.ajax({
                url: ctx + 'system/ward/selectWardByDeptId',
                type: 'POST',
                data: { deptId: deptId },
                success: function(result) {
                    wardSelect.empty();
                    if(result.code === 0 && result.data.length) {
                        result.data.forEach(ward => {
                            const isSelected = ward.id == [[${tPatient.wardId}]];
                            const option = new Option(
                                ward.wardNumber,
                                ward.id,
                                false,
                                ward.status !== 0
                            );
                            if(isSelected) option.selected = true;
                            wardSelect.append(option);
                        });
                        wardSelect.prop('disabled', false).trigger('change');
                    }
                }
            });
        });

        // 病房选择事件（500ms防抖）
        let wardTimer;
        $('#wardId').on('change', function() {
            clearTimeout(wardTimer);
            wardTimer = setTimeout(() => {
                const wardId = $(this).val();
                const bedSelect = $('#bedId');
                const patientId = [[${tPatient.id}]];
                bedSelect.prop('disabled', true).empty().append('<option value="">加载中...</option>');

                if (!wardId) return;

                // 加载床位
                $.ajax({
                    url: ctx + 'system/bed/selectBedByWardId',
                    type: 'POST',
                    data: {
                        wardId: wardId,
                        patientId: patientId
                    },
                    success: function(result) {
                        bedSelect.empty();
                        if(result.code === 0 && result.data.length) {
                            result.data.forEach(bed => {
                                const isAvailable = bed.isAvailable === 0;
                                const isSelected = bed.id == [[${tPatient.bedId}]];
                                const option = new Option(
                                    bed.bedNumber + (isAvailable ? '' : '（不可用）'),
                                    bed.id,
                                    false,
                                    !isAvailable
                                );
                                if(isSelected) option.selected = true;
                                bedSelect.append(option);
                            });
                            bedSelect.prop('disabled', false);
                        }
                    }
                });
            }, 500);
        });

        // 初始化级联选择
        const initDeptId = [[${tPatient.departmentId}]];
        if(initDeptId) {
            setTimeout(() => {
                $('#departmentId').trigger('change');
                setTimeout(() => {
                    $('#wardId').val([[${tPatient.wardId}]]).trigger('change');
                    setTimeout(() => {
                        $('#bedId').val([[${tPatient.bedId}]]);
                    }, 800);
                }, 800);
            }, 100);
        }

        // 日期选择器初始化
        $("input[name='birthDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        }).on('change', function() {
            calculateAge(this.value);
        });

        // 初始年龄计算
        const initBirthDate = [[${#dates.format(tPatient.birthDate, 'yyyy-MM-dd')}]];
        if(initBirthDate) calculateAge(initBirthDate);
    });

    // 年龄计算函数
    window.calculateAge = function(birthDate) {
        if (!birthDate) return;

        const birthParts = birthDate.split('-');
        const birthYear = parseInt(birthParts[0]);
        const birthMonth = parseInt(birthParts[1]) - 1;
        const birthDay = parseInt(birthParts[2]);

        const today = new Date();
        const birthDateObj = new Date(birthYear, birthMonth, birthDay);

        let age = today.getFullYear() - birthYear;
        const monthDiff = today.getMonth() - birthMonth;

        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDay)) {
            age--;
        }

        $("input[name='age']").val(age);
    };

    // 自定义验证规则
    $.validator.addMethod("validWard", function(value) {
        return $('#wardId option:not(:disabled)').length > 0;
    }, "请选择有效病房");

    $.validator.addMethod("validBed", function(value) {
        return $('#bedId option:selected').not(':disabled').length > 0;
    }, "请选择可用床位");
</script>
</body>
</html>